package add

import (
    "../balance"
    "fmt"
    "math/rand"
    "hash/crc32"
)

// 初始化就将该负载均衡算法注册到manager里
func init() {
    balance.RegisterBalance("hash", &HashBalance{})
}

type HashBalance struct {
    key string
}

func (p *HashBalance) DoBalance(insts [] *balance.Instance, key ...string) (inst *balance.Instance, err error) {
    // 相同的defKey会映射到相同的instance
    defKey := fmt.Sprintf("%d", rand.Int())
    if len(key) > 0 {
        defKey = key[0]
    }
    lens := len(insts)
    if lens == 0 {
        err = fmt.Errorf("no balance")
        return
    }
    hashVal := crc32.Checksum([]byte(defKey), crc32.MakeTable(crc32.IEEE))
    index := int(hashVal) % lens
    inst = insts[index]
    return
}